<template>
  <div>
    <div class="forgot-container">
      <!-- 粒子效果 -->
      <div class="particles-container" ref="particlesContainer"></div>
      
      <!-- 毛玻璃背景 -->
      <div class="glass-overlay"></div>
      
      <!-- 忘记密码表单 -->
      <div class="forgot-body" :class="{'form-transition': isFormChanging}" ref="forgotBody">
        <el-tooltip
          class="item"
          effect="dark"
          content="回到首页"
          placement="top"
        >
          <button class="back-btn" @click="backToHome">
            <i class="el-icon-back"></i>
          </button>
        </el-tooltip>

        <!-- 忘记密码表单 -->
        <div class="form-container">
          <div class="form-header">
            <h2 class="form-title">找回账号</h2>
            <p class="form-subtitle">重置密码,请输入您的邮箱</p>
          </div>
          <el-form :model="forgotForm" :rules="rules" ref="forgotForm">
            <el-form-item class="form-item" prop="email">
              <el-input
                prefix-icon="el-icon-message"
                v-model="forgotForm.email"
                placeholder="请输入注册邮箱"
              />
            </el-form-item>

            <el-form-item class="form-item" prop="code">
              <el-input
                prefix-icon="el-icon-key"
                v-model="forgotForm.code"
                placeholder="请输入验证码"
              >
                <template slot="append">
                  <el-button
                    @click="sendVerificationCode"
                    :disabled="codeSending"
                  >
                    {{ codeButtonText }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item class="form-item" prop="password">
              <el-input
                prefix-icon="el-icon-lock"
                v-model="forgotForm.password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>

            <el-form-item class="form-item">
              <el-button
                class="submit-btn"
                :loading="loading"
                @click="handleResetPassword"
              >
                重置密码
              </el-button>
            </el-form-item>

            <div class="form-switch">
              <a @click="goToLogin">返回登录</a>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { disableScroll, enableScroll } from "@/utils/scroll";
import { sendEmailCodeApi, forgotPasswordApi } from "@/api/auth";

export default {
  name: "ForgotPassword",
  data() {
    return {
      loading: false,
      forgotForm: {
        email: "",
        code: "",
        password: "",
      },
      codeSending: false,
      codeButtonText: "发送验证码",
      codeTimer: null,
      particlesArray: [],
      particlesCount: 200,
      isFormChanging: false,
      assemblyComplete: false,
      rules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  created() {
    this.$nextTick(() => {
      disableScroll();
    });
  },
  methods: {
    /**
     * 忘记密码
     */
    async handleResetPassword() {
      this.$refs["forgotForm"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            // 调用重置密码接口
            await forgotPasswordApi(this.forgotForm);
            this.$message.success("密码重置成功");
            this.goToLogin();
          } catch (error) {
            this.$message.error(error.message || "重置失败，请重试");
          } finally {
            this.loading = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    
    /**
     * 发送忘记密码邮箱验证码
     */
    async sendVerificationCode() {
      if (this.codeSending) return;

      if (!this.forgotForm.email) {
        this.$message.error("请先输入邮箱");
        return;
      }

      this.codeSending = true;
      this.sendEmailCode(this.forgotForm.email);
    },
    
    /**
     * 发送邮箱验证码
     */
    sendEmailCode(email) {
      sendEmailCodeApi(email)
        .then((res) => {
          this.$message.success("发送成功，请前往邮箱查看验证码");
          // 开始倒计时
          let countdown = 60;
          this.codeButtonText = `${countdown}秒后重试`;

          this.codeTimer = setInterval(() => {
            countdown--;
            if (countdown <= 0) {
              clearInterval(this.codeTimer);
              this.codeSending = false;
              this.codeButtonText = "发送验证码";
            } else {
              this.codeButtonText = `${countdown}秒后重试`;
            }
          }, 1000);
        })
        .catch((err) => {
          this.$message.error(err.message || "发送失败");
          this.codeSending = false;
        });
    },

    /**
     * 清理定时器
     */
    clearTimer() {
      if (this.codeTimer) {
        clearInterval(this.codeTimer);
      }
    },

    /**
     * 回到首页
     */
    backToHome() {
      this.$router.push("/");
    },
    
    /**
     * 前往登录页
     */
    goToLogin() {
      // 添加过渡动画效果
      this.isFormChanging = true;
      this.explodeParticles();
      
      // 隐藏当前表单
      const forgotBody = this.$refs.forgotBody;
      if (forgotBody) {
        forgotBody.style.opacity = '0';
      }
      
      setTimeout(() => {
        this.$router.push("/login");
      }, 800);
    },
    
    /**
     * 初始化粒子
     */
    initParticles() {
      const container = this.$refs.particlesContainer;
      if (!container) return;
      
      const width = window.innerWidth;
      const height = window.innerHeight;
      
      // 清空之前的粒子
      container.innerHTML = '';
      this.particlesArray = [];
      
      // 获取忘记密码表单的位置和尺寸
      const forgotBody = this.$refs.forgotBody;
      if (!forgotBody) return;
      
      const formRect = forgotBody.getBoundingClientRect();
      const formLeft = formRect.left;
      const formTop = formRect.top;
      const formWidth = formRect.width;
      const formHeight = formRect.height;
      
      // 计算粒子在表单上的分布密度
      const particlesPerRow = Math.ceil(Math.sqrt(this.particlesCount * (formWidth / formHeight)));
      const particlesPerCol = Math.ceil(this.particlesCount / particlesPerRow);
      const stepX = formWidth / particlesPerRow;
      const stepY = formHeight / particlesPerCol;
      
      let particleIndex = 0;
      
      // 创建粒子并分布在表单上的网格位置
      for (let row = 0; row < particlesPerCol; row++) {
        for (let col = 0; col < particlesPerRow; col++) {
          if (particleIndex >= this.particlesCount) break;
          
          // 最终位置会是表单上的网格点
          const targetX = formLeft + col * stepX + Math.random() * stepX;
          const targetY = formTop + row * stepY + Math.random() * stepY;
          
          // 初始位置是随机的
          const startX = Math.random() * width;
          const startY = Math.random() * height;
          
          // 随机大小 (3-8px) - 显著增大粒子尺寸
          const size = Math.random() * 5 + 3;
          
          // 随机颜色 - 使用更明亮的颜色
          const colors = ['#ffffff', '#f0f0ff', '#e8e8ff', '#f5f5ff', '#a0c4ff', '#bde0fe'];
          const color = colors[Math.floor(Math.random() * colors.length)];
          
          // 随机不透明度 - 提高不透明度使其更明显
          const opacity = Math.random() * 0.6 + 0.4;
          
          // 随机延迟 - 减少延迟以加快重组
          const delay = Math.random() * 500;
          
          // 创建粒子元素
          const particle = document.createElement('div');
          particle.classList.add('particle');
          
          // 设置样式
          particle.style.width = `${size}px`;
          particle.style.height = `${size}px`;
          particle.style.backgroundColor = color;
          particle.style.opacity = opacity;
          particle.style.transform = `translate(${startX}px, ${startY}px)`;
          
          // 将粒子信息存储在数组中
          this.particlesArray.push({
            element: particle,
            x: startX,
            y: startY,
            targetX,
            targetY,
            size,
            opacity,
            delay,
            speed: 1.0 + Math.random() * 1.5, // 增加速度以加快重组
            isAssembling: false,
            isAssembled: false
          });
          
          // 添加到容器
          container.appendChild(particle);
          particleIndex++;
        }
      }
      
      // 启动动画
      this.animateParticles();
      
      // 开始组装效果
      setTimeout(() => {
        this.assembleParticles();
      }, 300); // 减少等待时间
    },
    
    /**
     * 动画粒子
     */
    animateParticles() {
      const animate = () => {
        let allAssembled = true;
        
        this.particlesArray.forEach(particle => {
          // 如果粒子正在组装中
          if (particle.isAssembling && !particle.isAssembled) {
            allAssembled = false;
            
            // 计算粒子到目标的距离
            const dx = particle.targetX - particle.x;
            const dy = particle.targetY - particle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            // 如果距离很小，认为已经到达目标
            if (distance < 1) {
              particle.x = particle.targetX;
              particle.y = particle.targetY;
              particle.isAssembled = true;
              particle.element.style.boxShadow = '0 0 20px rgba(255, 255, 255, 0.95), 0 0 15px rgba(100, 200, 255, 0.9)';
            } else {
              // 否则继续向目标移动 - 提高速度
              particle.x += dx * 0.1 * particle.speed;
              particle.y += dy * 0.1 * particle.speed;
            }
            
            // 更新粒子位置
            particle.element.style.transform = `translate(${particle.x}px, ${particle.y}px)`;
          } else if (!particle.isAssembling) {
            allAssembled = false;
            
            // 自由移动逻辑 - 增加移动幅度
            particle.x += (Math.random() - 0.5) * 1.2;
            particle.y += (Math.random() - 0.5) * 1.2;
            
            // 更新粒子位置
            particle.element.style.transform = `translate(${particle.x}px, ${particle.y}px)`;
          }
        });
        
        // 如果所有粒子都组装完成
        if (allAssembled && !this.assemblyComplete) {
          this.assemblyComplete = true;
          // 在组装完成后稍微延迟显示表单
          setTimeout(() => {
            this.revealForgotForm();
          }, 100); // 减少等待时间
        }
        
        // 继续动画
        this.animationFrame = requestAnimationFrame(animate);
      };
      
      // 开始动画
      this.animationFrame = requestAnimationFrame(animate);
    },
    
    /**
     * 开始组装粒子到忘记密码表单
     */
    assembleParticles() {
      this.particlesArray.forEach((particle, index) => {
        setTimeout(() => {
          particle.isAssembling = true;
          particle.element.style.transition = `transform 1s cubic-bezier(0.165, 0.84, 0.44, 1)`;
        }, particle.delay);
      });
    },
    
    /**
     * 显示忘记密码表单
     */
    revealForgotForm() {
      const forgotBody = this.$refs.forgotBody;
      if (forgotBody) {
        forgotBody.style.opacity = '1';
        
        // 让粒子闪烁并逐渐消失
        this.particlesArray.forEach((particle, index) => {
          setTimeout(() => {
            particle.element.style.transition = 'opacity 1s ease-out';
            particle.element.style.opacity = '0';
          }, Math.random() * 1000);
        });
      }
    },
    
    /**
     * 爆炸效果 - 切换表单时
     */
    explodeParticles() {
      const forgotBody = this.$refs.forgotBody;
      if (!forgotBody) return;
      
      const formRect = forgotBody.getBoundingClientRect();
      const formCenterX = formRect.left + formRect.width / 2;
      const formCenterY = formRect.top + formRect.height / 2;
      
      this.particlesArray.forEach(particle => {
        // 计算粒子相对于表单中心的方向
        const dx = particle.x - formCenterX;
        const dy = particle.y - formCenterY;
        const distance = Math.sqrt(dx * dx + dy * dy) || 1;
        const normalizedDx = dx / distance;
        const normalizedDy = dy / distance;
        
        // 计算爆炸距离（边缘粒子飞得更远）
        const explosionForce = 500 + Math.random() * 400;
        
        // 设置爆炸动画 - 加快爆炸速度
        particle.element.style.opacity = '1';
        particle.element.style.transition = 'transform 0.3s cubic-bezier(0.165, 0.84, 0.44, 1), opacity 0.3s ease';
        particle.element.style.transform = `translate(${particle.x + normalizedDx * explosionForce}px, ${particle.y + normalizedDy * explosionForce}px)`;
        
        // 重置状态
        particle.isAssembled = false;
        particle.isAssembling = false;
      });
    },
    
    /**
     * 窗口调整大小
     */
    handleResize() {
      if (this.animationFrame) {
        cancelAnimationFrame(this.animationFrame);
      }
      
      // 重新初始化粒子
      this.initParticles();
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 等待DOM渲染完成后初始化粒子
      setTimeout(() => {
        this.initParticles();
        window.addEventListener('resize', this.handleResize);
      }, 100);
    });
  },
  beforeDestroy() {
    enableScroll();
    this.clearTimer();
    if (this.animationFrame) {
      cancelAnimationFrame(this.animationFrame);
    }
    window.removeEventListener('resize', this.handleResize);
  },
};
</script>
<style scoped lang="scss">
.forgot-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f6ad55 0%, #ed8936 100%);
  background-size: cover;
  min-height: 100vh;
  z-index: 2000;
  overflow: hidden;
}

/* 毛玻璃背景 */
.glass-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  z-index: 1;
}

/* 粒子效果 */
.particles-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  pointer-events: none;
  overflow: hidden;
}

.particle {
  position: absolute;
  background: white;
  border-radius: 50%;
  box-shadow: 0 0 20px rgba(255, 255, 255, 0.95), 0 0 10px rgba(100, 200, 255, 0.9);
  will-change: transform;
  z-index: 3;
  filter: blur(0.5px);
}

.forgot-body {
  width: 420px;
  padding: 32px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  position: relative;
  z-index: 10;
  opacity: 0;
  transition: transform 0.5s, opacity 0.5s;
}

.form-transition {
  opacity: 0;
  transform: scale(0.95);
}

@keyframes floatIn {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-container {
  animation: fadeIn 0.3s ease;
}

.form-item {
  margin-bottom: 20px;

  :deep(.el-input__inner) {
    height: 44px;
    font-size: 14px;
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(255, 255, 255, 0.5);
    transition: all 0.3s;

    &:focus {
      background: rgba(255, 255, 255, 0.95);
      box-shadow: 0 0 0 2px rgba(237, 137, 54, 0.2);
    }

    &::placeholder {
      color: #9ca3af;
    }
  }

  :deep(.el-input__prefix) {
    left: 12px;
    color: #6b7280;
  }
}

.submit-btn {
  width: 100%;
  height: 42px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;

  &:hover {
    background: linear-gradient(135deg, #ed8936, #dd6b20);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(237, 137, 54, 0.3);
  }

  &:active {
    transform: translateY(0);
  }
  
  &::after {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: rgba(255, 255, 255, 0.1);
    transform: rotate(45deg);
    transition: all 0.3s;
    opacity: 0;
  }
  
  &:hover::after {
    opacity: 1;
    transform: rotate(45deg) translateY(-50%);
  }
}

.form-switch {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 24px;
  color: #6b7280;
  font-size: 14px;

  a {
    color: #ed8936;
    text-decoration: none;
    font-weight: 500;
    cursor: pointer;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: -2px;
      left: 0;
      width: 0;
      height: 1px;
      background: #ed8936;
      transition: width 0.3s;
    }

    &:hover {
      color: #dd6b20;
      
      &::after {
        width: 100%;
      }
    }
  }
}

.form-header {
  text-align: center;
  margin-bottom: 32px;
}

.form-title {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px;
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.form-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.back-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.8);
  border: none;
  color: #6b7280;
  z-index: 2;

  &:hover {
    background: #fff;
    transform: translateX(-4px);
    color: #ed8936;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  i {
    font-size: 20px;
  }
}
</style> 